﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;
using System.Threading;

namespace DatabaseBackup.Library
{
    public static class Compression
    {
        public static string CompressFile(string fileName)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    // Wait for a second to avoid any access errors
                    Thread.Sleep(1000);

                    try
                    {
                        // Zip the file
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddFile(fileName);
                            zip.Save(Path.ChangeExtension(fileName, ".zip"));
                        }
                    }
                    catch (ZipException ex)
                    {
                        ErrorHandler.AddToErrorLog(ex);
                        return fileName;
                    }

                    // Wait a second and delete
                    Thread.Sleep(1000);

                    try
                    {
                        File.Delete(fileName);
                    }
                    catch (IOException ex)
                    {
                        ErrorHandler.AddToErrorLog(ex);
                        return Path.ChangeExtension(fileName, ".zip");
                    }

                    return Path.ChangeExtension(fileName, ".zip");
                }

                return fileName;
            }
            catch (Exception ex)
            {
                ErrorHandler.AddToErrorLog(ex);
            }

            return fileName;
        }
    }
}
